package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    public StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisClient redisClient;

    @Override
    public Result queryById(Long id) {

        // 解决缓存穿透
        Shop shop = redisClient
                .queryPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, RedisConstants.CACHE_SHOP_TTL, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);

        // 互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);

        // 使用逻辑过期来解决
//        Shop shop = queryWithLogicalExpire(id);

//        Shop shop=redisClient.queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY,id,Shop.class,this::getById,RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("获取物品失败");
        }
        return Result.ok(shop);
    }

    /**
     * 实现互斥锁，解决缓存击穿
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id){
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        // 1. 从缓存中查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        // 2. 判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 3. 存在，直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 判断命中的是否是空值
        if (shopJson != null) {
            //返回一个错误信息
            return null;
        }
        Shop shop=null;
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        // 4. 实现缓存重建
        // 4.1. 获取互斥锁
        try {
            String shopCache = stringRedisTemplate.opsForValue().get(shopKey);
            // 4.2. 判断是否获取成功
            if (!tryLock(lockKey)){
                int retryTime=50;
                // 4.3. 失败则休眠并重试
                while ((retryTime--)>0){
                    shopCache=stringRedisTemplate.opsForValue().get(shopKey);
                    if (StrUtil.isNotBlank(shopCache)){
                        //redis中有数据则直接返回
                        return JSONUtil.toBean(shopCache, Shop.class);
                    }else {
                        Thread.sleep(5);
                    }
                }
                return null;
            }else {
                // 再次查询redis
                shopCache=stringRedisTemplate.opsForValue().get(shopKey);
                if (StrUtil.isNotBlank(shopCache)){
                    return JSONUtil.toBean(shopCache,Shop.class);
                }
                // 4.4.  成功，根据id查询数据库
                shop = getById(id);
                // 5. 不存在，直接返回错误
                if (shop == null) {
                    // 将空值打入redis中
                    stringRedisTemplate.opsForValue().set(shopKey,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
                    // 返回错误信息
                    return null;
                }
                // 6. 存在，写入redis再返回
                stringRedisTemplate.opsForValue().set(shopKey,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 7. 释放互斥锁
            releaseLock(lockKey);
        }
        return shop;
    }

    /**
     * 解决缓存穿透
     * @param id
     * @return
     */
    public Shop queryPassThrough(Long id){
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        // 1. 从缓存中查询商铺缓存
        String shop = stringRedisTemplate.opsForValue().get(shopKey);
        // 2. 判断是否存在
        if (StrUtil.isNotBlank(shop)) {
            // 3. 存在，直接返回
            return JSONUtil.toBean(shop, Shop.class);
        }
        // 判断命中的是否是空值
        if (shop != null) {
            //返回一个错误信息
            return null;
        }

        // 4. 不存在，根据id查询数据库
        Shop shop1 = getById(id);
        // 5. 不存在，直接返回错误
        if (shop1 == null) {
            // 将空值打入redis中
            stringRedisTemplate.opsForValue().set(shopKey,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            // 返回错误信息
            return null;
        }
        // 6. 存在，写入redis再返回
        stringRedisTemplate.opsForValue().set(shopKey,JSONUtil.toJsonStr(shop1),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop1;
    }

    /**
     * 添加锁
     * @param key
     * @return
     * @date 2023-02-22 17:38
     */
    public boolean tryLock(String key){
        Boolean lockKey = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(lockKey);
    }

    /**
     * 释放锁
     * @param key
     * @date 2023-02-22 17:39
     */
    public void releaseLock(String key){
        stringRedisTemplate.delete(key);
    }




    /**
     * 封装逻辑时间存入redis中
     * @param id
     * @param expireSeconds
     * @date 2023-02-22 20:15
     */
    public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
        // 1. 查询店铺信息
        Shop shop = getById(id);
        Thread.sleep(200);
        // 2. 封装逻辑过期时间
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 3. 写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);

    /**
     * 实现逻辑过期，解决缓存穿透问题
     * @param id
     * @return
     */
    public Shop queryWithLogicalExpire(Long id){
        String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
        // 1. 从缓存中查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        // 2. 判断是否存在
        if (StrUtil.isBlank(shopJson)) {
            // 3. 不存在，直接返回
            return null;
        }

        // 4. 命中，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject)redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 5. 判断是否过期
        if (!expireTime.isBefore(LocalDateTime.now())){
            // 5.1. 未过期，直接返回店铺信息
            return shop;
        }
        // 5.2. 已过期，需要缓存重建
        // 6. 缓存重建
        // 6.1. 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        // 6.2. 判断获取互斥锁是否成功
        boolean isGetLock = tryLock(lockKey);
        // 6.3. 成功，开启独立线程，实现缓存重建
        if (isGetLock){
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    saveShop2Redis(id,20L);
                } catch (Exception e){
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    releaseLock(lockKey);
                }
            });
        }
        // 6.4. 返回商品信息（无论成功还是失败）
        return shop;


//        // 4. 不存在，根据id查询数据库
//        Shop shop1 = getById(id);
//        // 5. 不存在，直接返回错误
//        if (shop1 == null) {
//            // 将空值打入redis中
//            stringRedisTemplate.opsForValue().set(shopKey,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
//            // 返回错误信息
//            return null;
//        }
//        // 6. 存在，写入redis再返回
//        stringRedisTemplate.opsForValue().set(shopKey,JSONUtil.toJsonStr(shop1),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        return shop1;
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        // 1. 删除数据库
        updateById(shop);
        // 2. 删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY+shop.getId());
        // 3. 返回
        return Result.ok();
    }
}
